package com.example.essearchdemo.product;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Refresh;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import com.example.search.ProductIndexInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ProductIndexService {
    private static final Logger log = LoggerFactory.getLogger(ProductIndexService.class);

    private final ElasticsearchClient client;

    public ProductIndexService(ElasticsearchClient client) {
        this.client = client;
    }

    public void indexOne(Product p) throws IOException {
        IndexRequest.Builder<Product> builder = new IndexRequest.Builder<Product>()
                .index(ProductIndexInitializer.INDEX)
                .document(p)
                .refresh(Refresh.True);

        if (p.getId() != null && !p.getId().isEmpty()) {
            builder.id(p.getId());
        }

        client.index(builder.build());
    }

    public void bulkIndex(List<Product> products) throws IOException {
        BulkRequest.Builder br = new BulkRequest.Builder();
        for (Product p : products) {
            br.operations(op -> op.index(idx -> idx
                    .index(ProductIndexInitializer.INDEX)
                    .id(p.getId())
                    .document(p)
            ));
        }
        BulkResponse resp = client.bulk(br.refresh(Refresh.True).build());
        if (resp.errors()) {
            log.warn("Bulk indexing completed with errors: {}", resp);
        } else {
            log.info("Bulk indexed {} products successfully", products.size());
        }
    }
}